package com.imay.live.activity.authentication;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.StringUtil;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.dialog.Dialoger;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.PermissionsGrantActivity;
import com.imay.live.fragment.PopupMenuFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.model.MenuItemModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.DefaultDeniedPermissionHandler;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.update.CheckUpdateApp;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.AddCardAothView;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by lzx on 2017/04/20 0020.
 * 身份证认证
 */

public class AuthentCardActivity extends BaseRequestActivity implements PopupMenuFragment.OnMenuClickListener {
    private LinearLayout linearLayout;
    private AddCardAothView addbackCardAothView;
    private AddCardAothView addCardAothView;
    private Uri fileUri;
    private ArrayList<MenuItemModel> menuList;
    private static final int BUTTON_FACE = 0x100;
    private static final int BUTTON_BACK = 0x200;
    private static final int CAMERA = 0x300;//相机
    private static final int PHOTO = 0x400;//相册
    private static final String NAME = "NAME";//姓名
    private static final String NO = "NO";//身份证
    public static final int RECODE = 0x403;//跳转入口
    private int typeonclick;
    private String reallyname, NOid;
    private String identificationFrontUrl, identificationBackUrl;
    private TextView roundTextView;

    public static void startActivityForResult(Activity activity, String name, String no, int requestCode) {
        Intent starter = new Intent(activity, AuthentCardActivity.class);
        starter.putExtra(NAME, name);
        starter.putExtra(NO, no);
        activity.startActivityForResult(starter, requestCode);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.authent_cardlayout;
    }

    private class SDImageView extends ImageView {

        public SDImageView(Context context) {
            super(context);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int wsize = MeasureSpec.getSize(widthMeasureSpec);
            int hsize = wsize * 342 / 1125;
            setMeasuredDimension(wsize, hsize);
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.auto_title));
        linearLayout = $(R.id.src_linear);
        ScrollView scrollView = $(R.id.scrollView);
        scrollView.setBackgroundColor(getResources().getColor(R.color.bg_window));
        reallyname = getIntent().getStringExtra(NAME);
        NOid = getIntent().getStringExtra(NO);
        if (StringUtil.isEmpty(reallyname) || StringUtil.isEmpty(NOid)) {
            finish();
            return;
        }
        addCardAothView = new AddCardAothView(this);
        addCardAothView.settip(getResources().getString(R.string.auto_photo), getResources().getString(R.string.auto_fphoto));
        addCardAothView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeonclick = BUTTON_FACE;
                isPermission();
            }
        });
        linearLayout.addView(addCardAothView);
        menuList = new ArrayList<MenuItemModel>();
        menuList.add(new MenuItemModel(PHOTO, R.string.auth_menu_photo));
        menuList.add(new MenuItemModel(CAMERA, R.string.auth_menu_camera));
        addbackCardAothView = new AddCardAothView(this);
        addbackCardAothView.settip(getResources().getString(R.string.auto_bphoto), getResources().getString(R.string.auto_backphoto));
        addbackCardAothView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeonclick = BUTTON_BACK;
                isPermission();
            }
        });
        linearLayout.addView(addbackCardAothView);

        SDImageView imageView = new SDImageView(this);
        imageView.setImageResource(R.mipmap.bg_05_shimrz_show_id);
        LinearLayout.LayoutParams imgpar = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imgpar.topMargin = (int) getResources().getDimension(R.dimen.auto_imgtop);
        imgpar.gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout.addView(imageView, imgpar);

        TextView bottomText = new TextView(this);
        bottomText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.auto_bottom_sp));
        bottomText.setText(getResources().getString(R.string.auto_bottom));
        bottomText.setTextColor(getResources().getColor(R.color.text_75));
        LinearLayout.LayoutParams bottomP = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        bottomP.topMargin = (int) getResources().getDimension(R.dimen.auto_bottom_t);
        bottomP.bottomMargin = (int) getResources().getDimension(R.dimen.auto_bottom);
        bottomText.setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.addView(bottomText, bottomP);

        addSubmit(linearLayout, AuthentCardActivity.this);
    }

    private void isPermission() {
        PermissionsGrantActivity.grantPermissions(AuthentCardActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}
                , new DefaultDeniedPermissionHandler(AuthentCardActivity.this) {
                    @Override
                    public void onPermissionsResult(String[] grantedpermissions, String[] denied_permissions) {
                        if (denied_permissions == null) {
                            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), PopupMenuFragment.newInstance(menuList));
                        }
                    }

                    @Override
                    protected void onDialogChoice(int choice) {
                    }
                });
    }

    private void addSubmit(LinearLayout linearLayout, Context context) {
        roundTextView = new TextView(context);
        roundTextView.setGravity(Gravity.CENTER);
        roundTextView.setPadding(0, (int) getResources().getDimension(R.dimen.re_button_padding), 0, (int) getResources().getDimension(R.dimen.re_button_padding));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_HORIZONTAL;
        params.topMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
        params.bottomMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
        params.leftMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
        params.rightMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
        roundTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (StringUtil.isEmpty(identificationFrontUrl)) {
//                    ToastUtil.show(AuthentCardActivity.this, "身份证上传中或者上传失败，请稍等");
                    return;
                }
                if (StringUtil.isEmpty(identificationBackUrl)) {
//                    ToastUtil.show(AuthentCardActivity.this, "身份证上传中或者上传失败，请稍等");
                    return;
                }
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getResources().getString(R.string.str_loading));
                ProtoRequestHelper.task(ProtoHttpFactory.getrealNameSubmit(0, reallyname, NOid, identificationFrontUrl, identificationBackUrl)).setTag(this.hashCode()).request(new ProtoCallBack() {
                    @Override
                    public void onRequestSuccess(String command, String data) {
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                        Result<String> result = JSON.parseObject(data, new TypeReference<Result<String>>() {
                        }.getType());
                        if (result.result == com.imay.live.proto.ResultCode.CodeSuccess) {
                            setResult(Activity.RESULT_OK);
                            finish();
                            return;
                        } else {
                            ErrorResult.toastError(AuthentCardActivity.this, result.result);
                        }

                    }

                    @Override
                    public void onRequestError(String command, int code, String message) {
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                        ErrorResult.toastError(AuthentCardActivity.this, code);
                    }
                });
            }
        });
        roundTextView.setText(getResources().getString(R.string.auto_submit));
        roundTextView.setTextColor(getResources().getColor(R.color.text_ff));
        roundTextView.setBackground(getResources().getDrawable(R.drawable.shape_corner100_b2));
        linearLayout.addView(roundTextView, params);
    }

    private Uri CameraImage(int type) {
//        File file = ICUtils.getOutputMediaFile(AuthentCardActivity.this);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = ICUtils.getOutputMediaFile(AuthentCardActivity.this);
        if (file == null) {
            return null;
        }
        Uri url = null;
        if (Build.VERSION.SDK_INT > 23) {
            int targetSDKVer = getApplicationInfo().targetSdkVersion;
            if (targetSDKVer > 23) {
                url = FileProvider.getUriForFile(
                        this,
                        CheckUpdateApp.AUTHORITY,
                        file);
            }
        }
        if (url == null) {
            url = Uri.fromFile(file);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, url);
        startActivityForResult(intent, type);

//        ContentValues contentValues = new ContentValues(1);
//        contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
//        Uri url = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, url);
//        startActivityForResult(intent, type);

        return url;
    }

    private void CameraPick(int type) {
        try {
            Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(albumIntent, type);
        } catch (Exception var4) {
        }
    }


    int i = 0;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                File file = new File((String) msg.obj);
                i++;
                if (i > 10) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ToastUtil.show(AuthentCardActivity.this, getResources().getString(R.string.auth_photo_fail));
                    return;
                }
                if (file.exists()) {
                    if (file.length() == 0) {
                        Message msg0 = handler.obtainMessage(0);
                        msg0.obj = msg.obj;
                        handler.sendMessageDelayed(msg0, 500);
                    } else {
                        upFaceload((String) msg.obj);
                    }
                }
            } else if (msg.what == 1) {
                File file = new File((String) msg.obj);
                i++;
                if (i > 10) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ToastUtil.show(AuthentCardActivity.this, getResources().getString(R.string.auth_photo_fail));
                    return;
                }
                if (file.exists()) {
                    if (file.length() == 0) {
                        Message msg0 = handler.obtainMessage(1);
                        msg0.obj = msg.obj;
                        handler.sendMessageDelayed(msg0, 500);
                    } else {
                        upbackload((String) msg.obj);
                    }
                }
            }
        }
    };

    private void upFaceload(final String filepath) {
        UploadFileManager.getInstance().uploadPic(filepath, new UploadFileManager.UploadCallBack() {//正面上传
            @Override
            public void uploadSuccess(String fileUrl) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                identificationFrontUrl = fileUrl;
                GlideUtil.loadImage(addCardAothView.getIv_auth(), filepath);
                if (!StringUtil.isEmpty(identificationBackUrl)) {
                    if (roundTextView != null) {
                        roundTextView.setBackground(getResources().getDrawable(R.drawable.shape_corner100_9e));
                        roundTextView.invalidate();
                    }
                }
            }

            @Override
            public void uploadFailer(int errorCode, String errorMessage) {
                ToastUtil.show(AuthentCardActivity.this, errorMessage);
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            }
        });
    }

    void upbackload(final String filepath) {
        UploadFileManager.getInstance().uploadPic(filepath, new UploadFileManager.UploadCallBack() {//正面上传
            @Override
            public void uploadSuccess(String fileUrl) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                GlideUtil.loadImage(addbackCardAothView.getIv_auth(), filepath);
                identificationBackUrl = fileUrl;
                if (!StringUtil.isEmpty(identificationFrontUrl)) {
                    if (roundTextView != null) {
                        roundTextView.setBackground(getResources().getDrawable(R.drawable.shape_corner100_9e));
                        roundTextView.invalidate();
                    }
                }
            }

            @Override
            public void uploadFailer(int errorCode, String errorMessage) {
                ToastUtil.show(AuthentCardActivity.this, errorMessage);
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == BUTTON_FACE) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (!uri.isOpaque()) {
                        fileUri = uri;
                    }
                }
                identificationFrontUrl = null;
                String filepath = Dialoger.getPath(AuthentCardActivity.this, fileUri);
                if (TextUtils.isEmpty(filepath)) {
                    ToastUtil.show(AuthentCardActivity.this, R.string.str_img_error);
                    return;
                }
                File file = new File(filepath);
                i = 0;
                if (file.exists()) {
                    DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getResources().getString(R.string.str_loading));
                    if (file.length() == 0) {
                        Message msg = handler.obtainMessage(0);
                        msg.obj = filepath;
                        handler.sendMessageDelayed(msg, 500);
                        return;
                    }
                } else {
                    ToastUtil.show(AuthentCardActivity.this, getResources().getString(R.string.auth_photo_fail));
                    return;
                }
                upFaceload(filepath);
//                File file = ICUtils.getOutputMediaFile(AuthentCardActivity.this);
            } else if (requestCode == BUTTON_BACK) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (!uri.isOpaque()) {
                        fileUri = uri;
                    }
                }
                identificationBackUrl = null;
                String filepath = Dialoger.getPath(AuthentCardActivity.this, fileUri);
                if (TextUtils.isEmpty(filepath)) {
                    ToastUtil.show(AuthentCardActivity.this, R.string.str_img_error);
                    return;
                }
                File file = new File(filepath);
                i = 0;
                if (file.exists()) {
                    DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getResources().getString(R.string.str_loading));
                    if (file.length() == 0) {
                        Message msg = handler.obtainMessage(1);
                        msg.obj = filepath;
                        handler.sendMessageDelayed(msg, 500);
                        return;
                    }
                } else {
                    ToastUtil.show(AuthentCardActivity.this, getResources().getString(R.string.auth_photo_fail));
                    return;
                }
                upbackload(filepath);
            }
        }
    }


    @Override
    public void onMenuClick(int action) {
        if (PHOTO == action) {
            CameraPick(typeonclick);
        } else if (CAMERA == action) {
            fileUri = CameraImage(typeonclick);
        }
    }
}
